package com.ptu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录过滤器
 */
@WebFilter(urlPatterns = {"/ptuoa/*", "*.jsp", "*.html"})
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;

        HttpServletResponse resp = (HttpServletResponse) response;

        // 获取 Session
        Object emp = req.getSession().getAttribute("emp");

        // 获得用户发送的请求路径/ptuoa/empList.jsp?
        String uri = req.getRequestURI();
        // name=zs&pwd=123
        String queryString = req.getQueryString();

        if ("/ptuoa/tech.html".equals(uri) || "/ptuoa/login.jsp".equals(uri) || "/ptuoa/ptu/EmployeeServlet?method=empLogin".equals(uri + "?" + queryString)) {
            // 直接放行即可
            filterChain.doFilter(req, resp);
        } else {
            if (emp != null) {
                // 已经登录
                filterChain.doFilter(req, resp);
            } else {
                request.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
